package com.remist.dao.impl.jpa;

import java.util.LinkedList;
import java.util.List;

import javax.persistence.Query;

import org.springframework.orm.jpa.support.JpaDaoSupport;

import com.remist.dao.ProductTypeDao;
import com.remist.model.ProductType;

public class ProductTypeDaoImpl  extends JpaDaoSupport implements ProductTypeDao {

	public ProductType addProductType(ProductType productTypeBean) {
		getJpaTemplate().persist(productTypeBean); 
		return productTypeBean;
	}

	public boolean updateProductType(ProductType productTypeBean) {
		getJpaTemplate().merge(productTypeBean); 
		return true;
	}

	public boolean deleteProductType(ProductType productTypeBean) {
		ProductType productType = getJpaTemplate().find(ProductType.class, productTypeBean.getId());
        if (productType != null)
        {
            getJpaTemplate().remove(productType);
        } 
		return true;
	}

	public List<ProductType> listSonProductTypeByParentKey(ProductType productTypeBean) {
		List<ProductType> find = getJpaTemplate().find(" SELECT  p FROM ProductType p WHERE p.parentId="+productTypeBean.getParentId());
		return find;
	}

	public ProductType getProductTypeByKey(ProductType bean) {
		return getJpaTemplate().find(ProductType.class, bean.getId()); 
	}

	public ProductType getProductTypeByName(ProductType productTypeBean) {
		List<ProductType> find = getJpaTemplate().find(" SELECT  p FROM ProductType p WHERE p.name='"+productTypeBean.getName() +"'");
		if ( find.size() >=1 )
			return find.get( 0 );
		else 
			return null;
	}

	public ProductType getParentTypeByParentKey(ProductType bean) {
		return  getJpaTemplate().find(ProductType.class, bean.getParentId()); 
	}

	public int countSonByParentKey(ProductType productTypeParentBean) {
		Query query = getJpaTemplate().getEntityManager().createQuery("SELECT COUNT(p.parentId) FROM ProductType p WHERE p.parentId="+productTypeParentBean.getParentId());
		Number countResult=(Number) query.getSingleResult();
		return countResult.intValue();
	}

	public List<ProductType> listChilds(ProductType bean) {
		List<ProductType> find = getJpaTemplate().find(" SELECT  p FROM ProductType p WHERE p.parentId="+bean.getId() );
		return find;
	}

}
